﻿namespace UFIDA.U9C.Cust.ZL.API.BaseData
{
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Eventing.Reader;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Web.UI.WebControls;
    using System.Xml.Linq;
    using UFIDA.U9.AP.Payment;
    using UFIDA.U9.Base;
    using UFIDA.U9.Base.BaseBE.BaseCommon;
    using UFIDA.U9.Base.Contact;
    using UFIDA.U9.Base.FlexField.KeyFlexField;
    using UFIDA.U9.Base.Organization;
    using UFIDA.U9.Base.UserRole;
    using UFIDA.U9.CBO.FI.BankAccount;
    using UFIDA.U9.CBO.HR.Department;
    using UFIDA.U9.CBO.HR.Person;
    using UFIDA.U9.CBO.HR.Position;
    using UFIDA.U9.CBO.MFG.BOM;
    using UFIDA.U9.CBO.SCM.Item;
    using UFIDA.U9.CBO.SCM.Supplier;
    using UFIDA.U9.PM.PO;
    using UFIDA.U9.PM.Rcv;
    using UFIDA.U9.PR.PurchaseRequest;
    using UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO;
    using UFIDA.U9C.Cust.ZL.API.Utils;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Util.Context;

    /// <summary>
    /// DataOperate partial 
    /// </summary>	
    public partial class DataOperate
    {
        internal BaseStrategy Select()
        {
            return new DataOperateImpementStrategy();
        }
    }

    #region  implement strategy	
    /// <summary>
    /// Impement Implement
    /// 
    /// </summary>	
    internal partial class DataOperateImpementStrategy : BaseStrategy
    {
        public DataOperateImpementStrategy() { }
        IEnumerable<XElement> partNos = null;
        //log4net.ILog logger = log4net.LogManager.GetLogger("UFIDA.U9C.Cust.ZL.API.BaseData.DataOperateImpementStrategy");
        log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public override object Do(object obj)
        {

            ReturnDTO ret = new ReturnDTO();
            try
            {
                DataOperate bpObj = (DataOperate)obj;

                if (bpObj == null)
                {
                    throw new NotImplementedException("参数为空");
                }

                var filename = "APIConfig.xml";
                var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                var configXml = Path.Combine(currentDirectory, filename);

                XElement xmlInfo = XElement.Load(configXml);
                partNos = xmlInfo.Descendants("Element");

                //

                string authLoginUser = partNos.Where(p => p.Attribute("name")?.Value == "AuthLoginUser").FirstOrDefault()?.Value;
                string authLoginPwd = partNos.Where(p => p.Attribute("name")?.Value == "AuthLoginPwd").FirstOrDefault()?.Value;

                //组织
                if (bpObj.Type.Equals(((int)DealWithEnum.Org).ToString()))
                {
                    string orgUrl = partNos.Where(p => p.Attribute("name")?.Value == "Org").FirstOrDefault()?.Value;

                    string ids = string.Join(",", bpObj.IDs);
                    List<Organization> orgs = Organization.Finder.FindAll($"ID in ({ids})").OfType<Organization>().ToList();

                    RequestHelper request = new RequestHelper(authLoginUser, authLoginPwd);
                    OrgReqDTO orgReqDTO = new OrgReqDTO();
                    orgReqDTO.organizationDtoList = new List<OrganizationDto>();

                    foreach (var org in orgs)
                    {

                        orgReqDTO.organizationDtoList.Add(new OrganizationDto
                        {
                            id = org.ID.ToString(),
                            name = org.Name,
                            no = org.Code,
                            namePinyin = org.Name,
                            nameShortPinyin = org.ShortName,
                            orgTypeDk = "INNER",
                            deleted = bpObj.Operate == 2 ? true : false,
                            remark = org.Description

                        });

                    }

                    UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.POReturnDTO returnDTO = request.PostWebRequest(orgUrl, BaseJsonHelper.GetJsonJS(orgReqDTO));
                    if (returnDTO.body.status == "error")
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 2,
                            Message = "【SRM】" + returnDTO.body.message
                        };
                    }
                    else
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 1,
                            Message = "新增成功"
                        };
                    }


                }
                //部门
                else if (bpObj.Type.Equals(((int)DealWithEnum.Department).ToString()))
                {
                    string DepartmentUrl = partNos.Where(p => p.Attribute("name")?.Value == "Department").FirstOrDefault()?.Value;

                    string ids = string.Join(",", bpObj.IDs);
                    List<Department> departments = Department.Finder.FindAll($"ID in ({ids})").OfType<Department>().ToList();

                    RequestHelper request = new RequestHelper(authLoginUser, authLoginPwd);
                    DepartmentReqDTO departmentreqDTO = new DepartmentReqDTO();
                    departmentreqDTO.departmentDtoList = new List<DepartmentDTO>();

                    foreach (var dept in departments)
                    {
                        departmentreqDTO.departmentDtoList.Add(new DepartmentDTO
                        {
                            id = dept.ID.ToString(),
                            name = dept.Name,
                            no = dept.Code,
                            organizationId = dept.Org.ID.ToString(),
                            organizationNo = dept.Org.Code,
                            organizationName = dept.Org.Name,
                            parentNo = dept.ParentNode?.Code,
                            parentName = dept.ParentNode?.Name,
                            deleted = bpObj.Operate == 2 ? true : false,
                            remark = dept.Description

                        });

                    }
                    UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.POReturnDTO returnDTO = request.PostWebRequest(DepartmentUrl, BaseJsonHelper.GetJsonJS(departmentreqDTO));
                    if (returnDTO.body.status == "error")
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 2,
                            Message = "【SRM】" + returnDTO.body.message
                        };
                    }
                    else
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 1,
                            Message = "新增成功"
                        };
                    }
                }
                //人员
                //else if (bpObj.Type.Equals(DealWithEnum.Human.ToString()))
                //{
                //    string personUrl = partNos.Where(p => p.Attribute("name")?.Value == "Person").FirstOrDefault()?.Value;

                //    string ids = string.Join(",", bpObj.IDs);
                //    List<Person> persons = Person.Finder.FindAll($"ID in ({ids})").OfType<Person>().ToList();

                //    Request request = new Request(authLoginUser, authLoginPwd);
                //    PersonReqDTO personReqDTO = new PersonReqDTO();
                //    personReqDTO.personDtos = new List<PersonDTO>();

                //    foreach (var person in persons)
                //    {
                //        personReqDTO.personDtos.Add(new PersonDTO
                //        {
                //            no = person.EmployeeArchives.OfType<EmployeeArchive>().FirstOrDefault()?.EmployeeCode,
                //            masterAccountTypeDk = "MASTER",
                //            name = person.Name,
                //            genderDk = person.Sex.Name,
                //            remark = person.EmployeeArchives.OfType<EmployeeArchive>().FirstOrDefault()?.Remark,
                //            languageCode = "zh_CN",
                //            userTypeDk = "INNER_USER",
                //            phone = person.TelPhone,
                //            positionCodes = person.EmployeeArchives.OfType<EmployeeArchive>().FirstOrDefault()?.Position?.Code,
                //            managerName = person.EmployeeJobRelations.OfType<EmployeeJobRelation>()?.FirstOrDefault()?.SuperiorEmployee?.Name,
                //            managerNo = person.EmployeeJobRelations.OfType<EmployeeJobRelation>()?.FirstOrDefault()?.SuperiorEmployee?.EmployeeCode,
                //            costCenterNo = person.EmployeeArchives.OfType<EmployeeArchive>().FirstOrDefault()?.WorkingOrg.Name,//注意
                //            roleNames = "ROLE_INNER_USER",
                //            officePhone = person.EmployeeArchives.OfType<EmployeeArchive>().FirstOrDefault()?.ModifiedBy,
                //            title = person.EmployeeArchives.OfType<EmployeeArchive>().FirstOrDefault()?.Job.JobTitleLower.Name,
                //            rank,
                //            position,
                //            otherPhone,
                //            leaderNo,
                //            speciality,
                //            realNameAuthFlag,
                //            excelId,
                //            email,
                //            securityLevel,
                //            initialPassword,
                //            enableFlag,
                //            statusDk,
                //            orgName,
                //            orgNo,
                //            deptNo,
                //            login,
                //            updateRoleFlag,


                //        });

                //    }

                //    request.PostRequest(personUrl, BaseJsonHelper.GetJsonJS(departmentreqDTO));
                //}
                //料品分类
                else if (bpObj.Type.Equals(((int)DealWithEnum.ItemClass).ToString()))
                {
                    string itemcategoryUrl = partNos.Where(p => p.Attribute("name")?.Value == "ItemCategory").FirstOrDefault()?.Value;

                    string ids = string.Join(",", bpObj.IDs);
                    List<ItemCategory> itemCategories = ItemCategory.Finder.FindAll($"ID in ({ids})").OfType<ItemCategory>().ToList();

                    RequestHelper request = new RequestHelper(authLoginUser, authLoginPwd);
                    ItemCategoryReqDTO itemCategoryreqDTO = new ItemCategoryReqDTO();
                    itemCategoryreqDTO.mat_mat_category_c = new ItemCategoryDTO();

                    foreach (var category in itemCategories)
                    {
                        string code = category.Code;
                        //string treerule = category.KeyFlexFieldStru?.Segments.OfType<KeyFlexSegment>().FirstOrDefault().ValueSetDef.TreeRule;

                        itemCategoryreqDTO.mat_mat_category_c = new ItemCategoryDTO
                        {
                            code = category.Code,
                            name = category.Name,

                            parent_code = (code.Length >= 4) ? category.Code.Substring(0, 2) : string.Empty,
                            order_seq = "1",
                            enable_flag = bpObj.Operate == 2 ? "0" : "1",
                            remark = string.Empty

                        };

                    }
                    //Supplier supplier = Supplier.Finder.Find($"Code='31000001'");
                    //string supplierjson = Newtonsoft.Json.JsonConvert.SerializeObject(supplier);
                    //UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.ReturnDTO returnDTO = request.PostRequest(itemcategoryUrl, BaseJsonHelper.GetJsonJS(itemCategoryreqDTO));
                    UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.POReturnDTO returnDTO = request.PostWebRequest(itemcategoryUrl, BaseJsonHelper.GetJsonJS(itemCategoryreqDTO));
                    if (returnDTO.body.status == "error")
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 2,
                            Message = "【SRM】" + returnDTO.body.message
                        };
                    }
                    else
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 1,
                            Message = "新增成功"
                        };
                    }
                }
                //料品
                else if (bpObj.Type.Equals(((int)DealWithEnum.Item).ToString()))
                {
                    string itemUrl = partNos.Where(p => p.Attribute("name")?.Value == "Item").FirstOrDefault()?.Value;

                    string ids = string.Join(",", bpObj.IDs);
                    List<ItemMaster> items = ItemMaster.Finder.FindAll($"ID in ({ids})").OfType<ItemMaster>().ToList();

                    RequestHelper request = new RequestHelper(authLoginUser, authLoginPwd);
                    ItemReqDTO itemReqDTO = new ItemReqDTO();
                    itemReqDTO.mat_material_a = new ItemMainInfo();

                    foreach (var item in items)
                    {
                        itemReqDTO.mat_material_a = new ItemMainInfo
                        {
                            erp_code = item.Code,
                            name = item.Name,
                            mat_category_code = item.MainItemCategory?.Code,
                            specs = item.SPECS,
                            model = string.Empty,
                            brand = string.Empty,
                            origin_place = string.Empty,
                            danger_chemicals_flag = "0",
                            base_unit_code = item.InventoryUOM?.Code,//item.InventoryUOM ?.Name,//item.InventoryUOM?.Code,
                            pur_unit_code = item.PurchaseUOM?.Code,//item.PurchaseUOM?.Name,//item.PurchaseUOM?.Code,
                            order_price_unit = item.PurchaseUOM?.Code,
                            min_order_qty = item.PurchaseInfo.MinRcvQty,
                            purchase_method_dk = "01",
                            remark = item.Description,
                            lead_time = 0,
                            mfr = item.PurchaseInfo.Supplier?.Code,
                            min_package_qty = (int)item.PurchaseInfo.PurchaseBatchQty,
                            attachment_id = item.DescFlexField.PrivateDescSeg3,
                            material_type = "01"
                        };
                        itemReqDTO.mat_mat_unit_b = new List<ChangeUnit>();
                        foreach (var ratioOverClass in item.ItemConvertRatioOverClasses)
                        {
                            itemReqDTO.mat_mat_unit_b.Add(new ChangeUnit
                            {
                                base_unit_code = ratioOverClass.FromUOM?.Code,
                                cvt_unit_code = ratioOverClass.ToUOM?.Code,
                                cvt_to_base_den = "1",
                                cvt_to_base_mol = ratioOverClass.Ratio.ToString()
                            });
                        }
                        itemReqDTO.mat_plant_mat_a = new List<ItemFactory>();

                    }

                    //UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.ReturnDTO returnDTO = request.PostRequest(itemUrl, BaseJsonHelper.GetJsonJS(itemReqDTO));

                    //string ret1 = request.Post(itemUrl, Newtonsoft.Json.JsonConvert.SerializeObject((itemReqDTO)));--历史使用
                    ret = null;
                    UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.POReturnDTO returnDTO = request.PostWebRequest(itemUrl, BaseJsonHelper.GetJsonJS(itemReqDTO));
                    if (returnDTO.body.status == "error")
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 2,
                            Message = "SRM:" + returnDTO.body.message
                        };
                    }
                    else
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 1,
                            Message = "新增成功"
                        };
                    }

                }
                //请购单、委外请购
                else if (bpObj.Type.Equals(((int)DealWithEnum.POApply).ToString()))
                {
                    string poApplyUrl = partNos.Where(p => p.Attribute("name")?.Value == "POApply").FirstOrDefault()?.Value;
                    IEnumerable<PR> PRs = null;
                    if (bpObj.Operate == 1 || bpObj.Operate == 2 || bpObj.Operate == 3 || bpObj.Operate == 5)
                    {
                        string ids = string.Join(",", bpObj.IDs);

                        PRs = PR.Finder.FindAll($"ID in ({ids})").OfType<PR>();
                    }
                    else if (bpObj.Operate == 4 || bpObj.Operate == 6)
                    {
                        string ids = string.Join(",", bpObj.IDs);

                        PRs = PRLine.Finder.FindAll($"ID in ({ids})").OfType<PRLine>().Select(p => p.PR).OfType<PR>();
                    }
                    if (PRs.Any())
                    {
                        RequestHelper request = new RequestHelper(authLoginUser, authLoginPwd);

                        //
                        //if (!PRs.Where(p => p.PRLineList.OfType<PRLine>().Where(p => p.BizType.Value == 325 || p.BizType.Value == 326).Any()).Any())

                        foreach (var pr in PRs)
                        {
                            PRApplyReqDTO PRReqDTO = new PRApplyReqDTO();
                            User user = User.Finder.Find($"Name='{pr.CreatedBy}'");
                            if (user == null)
                            {
                                throw new Exception($"单据创建人{pr.CreatedBy}不存在");
                            }
                            PRReqDTO.dmd_pur_req_a = new PRHead()
                            {
                                no = pr.DocNo,
                                type_code = pr.DocType.Code,
                                plant_code = pr.LegacyOrg.Code,
                                company_code = pr.LegacyOrg.Code,
                                remark = pr.Memo,
                                created_by = user?.Code
                            };
                            PRReqDTO.dmd_pur_req_dtl_a = new List<PRBody>();
                            PRReqDTO.dmd_pur_req_dtl_comp_b = new List<OPRBody>();
                            foreach (PRLine prLine in pr.PRLineList.OfType<PRLine>())
                            {
                                #region 计算行打开关闭状态
                                string deleteflag = "0";
                                if (bpObj.Operate == 1)
                                {
                                    deleteflag = "0";
                                }
                                else if (bpObj.Operate == 2)
                                {
                                    deleteflag = "1";
                                }
                                else if (bpObj.Operate == 3)
                                {
                                    deleteflag = "1";

                                }
                                else if (bpObj.Operate == 5)
                                {
                                    deleteflag = "0";
                                }
                                else if (bpObj.Operate == 4)
                                {
                                    //核准
                                    if (prLine.Status.Value == 2)
                                    {
                                        deleteflag = "0";
                                    }
                                    else if (prLine.Status.Value == 4 || prLine.Status.Value == 3 || prLine.Status.Value == 5)
                                    {
                                        deleteflag = "1";
                                    }
                                    //行关闭

                                    if (bpObj.IDs.Contains(prLine.ID))
                                    {
                                        deleteflag = "1";
                                    }

                                }
                                else if (bpObj.Operate == 6)
                                {
                                    //核准
                                    if (prLine.Status.Value == 2)
                                    {
                                        deleteflag = "0";
                                    }
                                    else if (prLine.Status.Value == 4 || prLine.Status.Value == 3 || prLine.Status.Value == 5)
                                    {
                                        deleteflag = "1";
                                    }
                                    //行打开

                                    if (bpObj.IDs.Contains(prLine.ID))
                                    {
                                        deleteflag = "0";
                                    }


                                }
                                #endregion

                                //标准请购，委外请购
                                PRReqDTO.dmd_pur_req_dtl_a.Add(new PRBody
                                {
                                    item_no = prLine.DocLineNo.ToString(),
                                    mat_code = prLine.ItemInfo.ItemCode,
                                    mat_name = prLine.ItemInfo.ItemName,
                                    mat_erp_code = prLine.ItemInfo.ItemCode,
                                    //2024 /12 /27 改成主分类
                                    //mat_category_code = prLine.ItemInfo.ItemID.PurchaseCategory?.Code,
                                    mat_category_code = prLine.ItemInfo.ItemID.MainItemCategory?.Code,
                                    pur_type_dk = (prLine.BizType.Value == 325 || prLine.BizType.Value == 326) ? "L" : "0",
                                    req_qty = prLine.ApprovedQtyPU,
                                    base_unit_code = prLine.TradeBaseUOM.Code,
                                    unit_code = prLine.PriceUOM.Code,
                                    pur_to_base_denominator = 1,
                                    pur_to_base_molecular = 1,
                                    exp_dlv_date = prLine.RequiredDeliveryDate.ToString("yyyy-MM-dd"),
                                    price_unit_qty = "1",
                                    plant_code = prLine.RcvOrg.Code,
                                    company_code = pr.LegacyOrg.Code,
                                    purorg_code = pr.LegacyOrg.Code,
                                    storage_code = prLine.Warehouse?.Code,
                                    //remark = prLine.Memo,
                                    remark = ((string.IsNullOrEmpty(prLine.Memo) ? string.Empty : prLine.Memo + "；") + prLine.DescFlexSegments.PrivateDescSeg1),
                                    //remark = prLine.DescFlexSegments.PrivateDescSeg1,
                                    created_by = prLine.ReqEmployee?.Code,
                                    pur_person = prLine.PurPerson?.Code,
                                    outfit = prLine.SeiBanCode,
                                    supplier_code = prLine.SuggestedSupplier?.Supplier?.Code,
                                    old_mat_code = prLine.ItemInfo.ItemID.Code1,
                                    specs = prLine.ItemInfo.ItemID.SPECS,
                                    delete_flag = deleteflag,
                                    close_flag = "0"


                                });
                                //委外
                                if (prLine.BizType.Value == 325 || prLine.BizType.Value == 326)
                                {
                                    BOMMaster bommaster = BOMMaster.Finder.Find($"ItemMaster.Code='{prLine.ItemInfo.ItemID.Code}' and Org={Context.LoginOrg.ID}");
                                    if (bommaster != null)
                                    {
                                        foreach (var child in bommaster.BOMComponents.OfType<BOMComponent>())
                                        {
                                            PRReqDTO.dmd_pur_req_dtl_comp_b.Add(new OPRBody
                                            {

                                                item_no = child.Sequence.ToString(),
                                                material_code = child.ItemMaster.Code,
                                                required_qty = (prLine.ApprovedQtyPU * child.UsageQty * child.ParentQty).ToString(),

                                                entry_unit_code = child.ItemMaster.InventoryUOM.Code,
                                                plant_code = child.IssueOrg.Code,
                                                required_date = prLine.RequiredDeliveryDate.ToString("yyyy-MM-dd")

                                            });
                                        }
                                    }
                                }
                            }

                            //UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.ReturnDTO returnDTO = request.PostRequest(poApplyUrl, BaseJsonHelper.GetJsonJS(PRReqDTO));
                            //ret = new ReturnDTO()
                            //{
                            //    Code = returnDTO.SERVICE_STATUS.Equals("S", StringComparison.OrdinalIgnoreCase) ? 1 : 2,
                            //    Message = returnDTO.message
                            //};
                            UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.POReturnDTO returnDTO = request.PostWebRequest(poApplyUrl, BaseJsonHelper.GetJsonJS(PRReqDTO));
                            if (returnDTO.SERVICE_STATUS == "E")
                            {
                                ret = new ReturnDTO()
                                {
                                    Code = 2,
                                    Message = "SRM:" + returnDTO.SERVICE_MESSAGE
                                };
                            }
                            else
                            {
                                ret = new ReturnDTO()
                                {
                                    Code = 1,
                                    Message = "新增成功"
                                };
                            }

                        }




                    }
                }
                //入库
                else if (bpObj.Type.Equals(((int)DealWithEnum.Instock).ToString()))
                {
                    string inStockUrl = partNos.Where(p => p.Attribute("name")?.Value == "InStock").FirstOrDefault()?.Value;

                    string ids = string.Join(",", bpObj.IDs);
                    var RCVs = Receivement.Finder.FindAll($"ID in ({ids})").OfType<Receivement>();
                    if (RCVs.Any())
                    {
                        RequestHelper request = new RequestHelper(authLoginUser, authLoginPwd);


                        foreach (var rcv in RCVs)
                        {
                            RcvReqDTO rcvReqDTO = new RcvReqDTO();
                            //rcvReqDTO.exe_storage_order_b = new RcvHead();
                            rcvReqDTO.exe_storage_order_b = new RcvHead()
                            {
                                no = rcv.DocNo,
                                doc_date = rcv.BusinessDate.ToString("yyyy-MM-dd"),
                                doc_type_dk = "PURCHASE_RECEIVED",
                                movement_type_dk = "101",
                                posting_date = rcv.RcvLines.OfType<RcvLine>().Select(p => new { p.ConfirmDate }).FirstOrDefault().ConfirmDate.ToString("yyyy-MM-dd"),
                                remark = rcv.Memo,

                            };

                            rcvReqDTO.exe_storage_order_dtl_b = new List<RcvDetail>();
                            foreach (RcvLine rcvline in rcv.RcvLines.OfType<RcvLine>())
                            {
                                string asndocno = rcvline.RcvLineExt.SrcASNInfo.SrcDocNo;
                                string asnlineno = rcvline.RcvLineExt.SrcASNInfo.SrcDocLineNo.ToString();

                                //拆后行
                                if (rcvline.SplitFlag.Value != 1)
                                {


                                    rcvReqDTO.exe_storage_order_dtl_b.Add(new RcvDetail
                                    {
                                        item_no = rcvline.DocLineNo.ToString(),
                                        material_code = rcvline.ItemInfo.ItemCode,
                                        material_name = rcvline.ItemInfo.ItemName,
                                        order_no = rcvline.SrcPO.SrcDocNo,
                                        order_item_no = rcvline.SrcPO.SrcDocLineNo.ToString(),
                                        supplier_code = rcvline.ConfirmSupplier?.Supplier?.Code,
                                        supplier_code_show = rcvline.ConfirmSupplier?.Supplier?.Name,
                                        plant_code = rcvline.OwnOrg.Code,
                                        qty = rcvline.RcvQtyTU.ToString(),
                                        movement_type_dk = "101",
                                        inventory_type_dk = "F",
                                        unit_code = rcvline.StoreUOM.Code,
                                        unit_code_show = rcvline.StoreUOM.Name,
                                        reference_doc_no = rcvline.SrcDoc.SrcDocNo,
                                        reference_doc_item_no = rcvline.SrcDoc.SrcDocLineNo.ToString(),
                                        remark = rcvline.Memo,
                                        storage_location_code = rcvline.Wh?.Code,
                                        storage_location_code_show = rcvline?.Wh.Name,
                                        isqcfree = rcvline.IsQCfree.ToString(),
                                        qcbillno = rcvline.QCBillNo,
                                        mrbno = rcvline.MRBNo,
                                        qcconclusion = rcvline.QCConclusion.Name,
                                        qcqcconclusion = rcvline.QCQCConclusion.Name,
                                        submitchecttime = rcvline.SubmitChectTime.ToString("yyyy-MM-dd"),
                                        delivery_note_no = asndocno,
                                        delivery_note_item_no = asnlineno


                                    });
                                }
                            }

                            UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.POReturnDTO returnDTO = request.PostWebRequest(inStockUrl, BaseJsonHelper.GetJsonJS(rcvReqDTO));
                            if (returnDTO.body.status == "error")
                            {
                                ret = new ReturnDTO()
                                {
                                    Code = 2,
                                    Message ="SRM:" +returnDTO.body.message
                                };
                            }
                            else
                            {
                                ret = new ReturnDTO()
                                {
                                    Code = 1,
                                    Message = "新增成功"
                                };
                            }
                        }


                    }
                }
                //采购退货
                else if (bpObj.Type.Equals(((int)DealWithEnum.POReturn).ToString()))
                {
                    string inStockUrl = partNos.Where(p => p.Attribute("name")?.Value == "InStock").FirstOrDefault()?.Value;

                    string ids = string.Join(",", bpObj.IDs);
                    List<Receivement> RCVs = Receivement.Finder.FindAll($"ID in ({ids})").OfType<Receivement>().ToList();

                    RequestHelper request = new RequestHelper(authLoginUser, authLoginPwd);


                    foreach (var rcv in RCVs)
                    {

                        RcvReqDTO rcvReqDTO = new RcvReqDTO();

                        rcvReqDTO.exe_storage_order_b = new RcvHead()
                        {
                            no = rcv.DocNo,
                            doc_date = rcv.BusinessDate.ToString("yyyy-MM-dd"),
                            doc_type_dk = "PURCHASE_RECEIVED",
                            movement_type_dk = "102",
                            posting_date = rcv.RcvLines.OfType<RcvLine>().Select(p => new { p.ConfirmDate }).FirstOrDefault().ConfirmDate.ToString("yyyy-MM-dd"),
                            remark = rcv.Memo,

                        };
                        rcvReqDTO.exe_storage_order_dtl_b = new List<RcvDetail>();
                        foreach (RcvLine rcvline in rcv.RcvLines.OfType<RcvLine>())
                        {

                            if (rcvline.SplitFlag.Value != 1)
                            {

                                rcvReqDTO.exe_storage_order_dtl_b.Add(new RcvDetail
                                {
                                    item_no = rcvline.DocLineNo.ToString(),
                                    material_code = rcvline.ItemInfo.ItemCode,
                                    material_name = rcvline.ItemInfo.ItemName,
                                    order_no = rcvline.SrcPO.SrcDocNo,
                                    order_item_no = rcvline.SrcPO.SrcDocLineNo.ToString(),
                                    supplier_code = rcvline.ConfirmSupplier?.Supplier?.Code,
                                    supplier_code_show = rcvline.ConfirmSupplier?.Supplier?.Name,
                                    plant_code = rcvline.OwnOrg.Code,
                                    qty = "-" + rcvline.RejectQtyTU.ToString(),
                                    movement_type_dk = "102",
                                    inventory_type_dk = "F",
                                    unit_code = rcvline.StoreUOM.Code,
                                    unit_code_show = rcvline.StoreUOM.Name,
                                    reference_doc_no = rcvline.SrcDoc.SrcDocNo,
                                    reference_doc_item_no = rcvline.SrcDoc.SrcDocLineNo.ToString(),
                                    remark = rcvline.Memo,
                                    storage_location_code = rcvline.Wh?.Code,
                                    storage_location_code_show = rcvline?.Wh.Name,


                                });
                            }
                        }
                        //UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.ReturnDTO returnDTO = request.PostRequest(inStockUrl, BaseJsonHelper.GetJsonJS(rcvReqDTO));
                        //ret = new ReturnDTO()
                        //{
                        //    Code = returnDTO.status.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase) ? 1 : 2,
                        //    Message = returnDTO.message
                        //};

                        UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.POReturnDTO returnDTO = request.PostWebRequest(inStockUrl, BaseJsonHelper.GetJsonJS(rcvReqDTO));
                        if (returnDTO.body.status == "error")
                        {
                            ret = new ReturnDTO()
                            {
                                Code = 2,
                                Message = "SRM:" + returnDTO.body.message
                            };
                        }
                        else
                        {
                            ret = new ReturnDTO()
                            {
                                Code = 1,
                                Message = "新增成功"
                            };
                        }

                    }


                }
                //付款单
                else if (bpObj.Type.Equals(((int)DealWithEnum.Payment).ToString()))
                {
                    string payUrl = partNos.Where(p => p.Attribute("name")?.Value == "Pay").FirstOrDefault()?.Value;

                    string ids = string.Join(",", bpObj.IDs);
                    List<PayBillHead> payBillHeads = PayBillHead.Finder.FindAll($"ID in ({ids})").OfType<PayBillHead>().ToList();

                    RequestHelper request = new RequestHelper(authLoginUser, authLoginPwd);

                    foreach (var paybillhead in payBillHeads)
                    {
                        PayReqDTO payReqDTO = new PayReqDTO();
                        payReqDTO.body = new Body();
                        payReqDTO.body.ba_payment_b = new PayDTO()
                        {
                            no = paybillhead.DocNo,
                            supplier_code = paybillhead.Supp?.Supplier?.Code,
                            company_code = paybillhead.Org.Code,
                            payment_amount = paybillhead.PayBillLines.OfType<PayBillLine>().Sum(p => p.TotalMoney?.OCMoney).ToString(),
                            currency_code = paybillhead.PC.Symbol,
                            payment_method = paybillhead.PayBillLines.OfType<PayBillLine>().FirstOrDefault().SettlementMethod.Name,
                            payment_date = paybillhead.PayDate.ToString("yyyy-MM-dd"),
                            src_system_dk = "OA",
                            remark = paybillhead.Memo

                        };
                        //UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.ReturnDTO returnDTO = request.PostRequest(payUrl, BaseJsonHelper.GetJsonJS(payReqDTO));
                        //ret = new ReturnDTO()
                        //{
                        //    Code = returnDTO.status.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase) ? 1 : 2,
                        //    Message = returnDTO.message
                        //};
                        UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.POReturnDTO returnDTO = request.PostWebRequest(payUrl, BaseJsonHelper.GetJsonJS(payReqDTO));
                        if (returnDTO.body.status == "error")
                        {
                            ret = new ReturnDTO()
                            {
                                Code = 2,
                                Message = "SRM:" + returnDTO.body.message
                            };
                        }
                        else
                        {
                            ret = new ReturnDTO()
                            {
                                Code = 1,
                                Message = "新增成功"
                            };
                        }

                    }
                }
                //采购订单同步至SRM
                else if (bpObj.Type.Equals(((int)DealWithEnum.PO).ToString()) && bpObj.IDs.Count > 0)
                {
                    UFIDA.U9.PM.PO.PurchaseOrder PO = UFIDA.U9.PM.PO.PurchaseOrder.Finder.FindByID(bpObj.IDs[0]);
                    SRMPO modelDto = new SRMPO(PO);

                    string itemcategoryUrl = partNos.Where(p => p.Attribute("name")?.Value == "PO").FirstOrDefault()?.Value;
                    RequestHelper request = new RequestHelper(authLoginUser, authLoginPwd,logger);

                    UFIDA.U9C.Cust.ZL.API.DTO.SRMDTO.POReturnDTO returnDTO = request.PostWebRequest(itemcategoryUrl, BaseJsonHelper.GetJsonJS(modelDto));                    
                    if (returnDTO.body.status == "error")
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 2,
                            Message = returnDTO.body.message
                        };
                    }
                    else
                    {
                        ret = new ReturnDTO()
                        {
                            Code = 1,
                            Message = "新增成功"
                        };
                    }
                   ;
                }

            }
            catch (Exception ex)
            {

                ret.Code = 2;
                ret.Message = ex.Message;
                logger.Error("【U9-SRM】" + ex.Message + "\r\n" + ex.StackTrace);
            }


            return ret;
        }
    }

    #endregion


}